package com.pig4cloud.pigx.contract.config.mongo;

import org.bson.types.Decimal128;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.convert.ReadingConverter;
import org.springframework.data.convert.WritingConverter;
import org.springframework.data.mongodb.core.convert.MongoCustomConversions;

import java.math.BigDecimal;
import java.util.Arrays;

/**
 * MongoDB 转换器设置
 *
 * @since 2022/8/22 18:00
 */
@Configuration
public class MongoConverterConfig {
	/**
	 * 注册转换器
	 *
	 * @return {@link MongoCustomConversions}
	 * @since 2022/8/22 18:00
	 */
	@Bean
	public MongoCustomConversions mongoCustomConversions() {
		return new MongoCustomConversions(Arrays.asList(
				new BigDecimalWriteConverter(),
				new BigDecimalReaderConverter()
		));

	}

	@WritingConverter
	private static class BigDecimalWriteConverter implements Converter<BigDecimal, Decimal128> {
		@Override
		public Decimal128 convert(BigDecimal source) {
			return new Decimal128(source);
		}
	}

	@ReadingConverter
	private static class BigDecimalReaderConverter implements Converter<Decimal128, BigDecimal> {
		@Override
		public BigDecimal convert(Decimal128 source) {
			return source.bigDecimalValue();
		}
	}
}
